<?
// 
//		Gallery Dataset class v1.5, 2008.09.22
//
//		init params:
//			$fn				path to gallery directory
//			$tn				name of the thumbnails directory

class GALLERY {

	var $fn;				// path to gallery directory
	var $tn;				// name of the thumbnails directory

	var	$data;				// результат
	
	var $res;				// код ошибки	
	
	var $PREXT;				// possible extensions of preview


	var $err = array (
		0 => 'success',
		1 => 'bad image or image not found',
		2 => 'no file selected',
		255 => 'not initialized'
	);
	
	function GALLERY() {

		$this->fn = '';
		$this->tn = '';
		$this->PREXT = array('jpg', 'JPG', 'gif', 'GIF');
	
		$this->data = array();
		
		$this->res = -255;
	}

	function init( $fn, $tn = 'tn' ) {
	
		$this->tn = $tn;
		
		if ($fn) {

			$this->fn = $fn;
	
			$this->res = $this->fetch();
		}
			else $this->res = 2;	// проект не выбран

		return ! (bool) $this->res;
	}


	function fetch() {

		$path = $_SERVER['DOCUMENT_ROOT'].$this->fn;

		$_files = $_previews = array();

		foreach (glob("$path/*.*") as $temp) {
			if ((is_file($temp)) && @filesize($temp) && ($is = @getimagesize($temp)) ) {
				$t = $this->parse_fname($temp);
				$_files[$t['name']] = array('w' => $is[0], 'h' => $is[1], 'fn' => "$t[name].$t[ext]" );
			}
		}

		foreach (glob("$path/{$this->tn}/*.*") as $temp) {
			if ((is_file($temp)) && @filesize($temp) && ($is = @getimagesize($temp)) ) {
				$t = $this->parse_fname($temp);
				$_previews[$t['name']] = array('w' => $is[0], 'h' => $is[1], 'fn' => "$t[name].$t[ext]" );
		}
		}
		
		foreach ($_previews as $k => $v)
			if (isset($_files[$k])) {
				$this->data[$_files[$k]['fn']] = array('w' => $_files[$k]['w'], 'h' => $_files[$k]['h'], 'fn' => $_files[$k]['fn'], 'tnw' => $v['w'], 'tnh' => $v['h'], 'tn' => "{$this->tn}/$v[fn]" );
				unset($_files[$k]);
			}
			else
				$this->data[$v['fn']] = array('tnw' => $v['w'], 'tnh' => $v['h'], 'tn' => "{$this->tn}/$v[fn]" );
		
		foreach ($_files as $k => $v)
			$this->data[$v['fn']] = array('w' => $v['w'], 'h' => $v['h'], 'fn' => $v['fn']);

		if (sizeof($this->data))
			return 0;
		else 
			return 1;	// no images
	}
	
	function parse_fname($fname) {
		if (($slash = strrpos($fname, '/')) === false) {
			$fn = $fname;
			$path = '';
		} else {
			$fn = substr($fname, $slash + 1);
			$path = substr($fname, 0, $slash);
		}
		preg_match('/(.+)\.(\w+)$/', $fn, $regs);
		return array('path' => $path, 'name' => $regs[1], 'ext' => $regs[2]);
	}

	function has_preview($path,$fname) {
		
			$nm = $this->parse_fname($fname);
			switch(strtolower($nm['ext'])) {
				case 'jpg':
				case 'gif':
				case 'png':
	
					foreach ($this->PREXT as $ext) {
						if (is_file("$path/{$this->tn}/$nm[name].$ext"))
							return "{$this->tn}/$nm[name].$ext";
					}
	
				break;
				
				default:
					return false;	// unknown extension
			}
			return false;	//	no preview
	}


}

?>